package com.mytrip.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter{
	private static final Log log = LogFactory.getLog(DateConverter.class);
	
	private final static String regex_datetime_s = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}";

	private final static SimpleDateFormat sdf_datetime_s = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	
	private final static String regex_datetime = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}";

	private final static SimpleDateFormat sdf_datetime = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");

	private final static String regex_time = "[0-9]{1,2}:[0-9]{1,2}";

	private final static SimpleDateFormat sdf_time = new SimpleDateFormat(
			"HH:mm");

	private final static String regex_date = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}";

	private final static SimpleDateFormat sdf_date = new SimpleDateFormat(
			"yyyy-MM-dd");

	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		if (values.length == 1) {
			Date date = null;
			try {
				date = convertToDate(values[0]);
			} catch (Exception e) {
				log.warn(e.getMessage());
			}
			return date;
		}

		Date[] results = new Date[values.length];

		for (int i = 0; i < values.length; i++) {
			String value = values[i];
			try {
				results[i] = convertToDate(value);
			} catch (Exception e) {
				log.warn(e.getMessage());
			}
		}

		return results;
	}

	private Date convertToDate(String value) throws Exception {
		value=value.trim();
		if (value.matches(regex_datetime_s))
			return sdf_datetime_s.parse(value);
		else if (value.matches(regex_datetime))
			return sdf_datetime.parse(value);
		else if (value.matches(regex_date))
			return sdf_date.parse(value);
		else if (value.matches(regex_time))
			return sdf_time.parse(value);

		return null;
	}

	@Override
	public String convertToString(Map context, Object o) {
		if (o instanceof Date) {
			Date date = (Date) o;
			return sdf_datetime.format(date);
		}

		return o.toString();
	}
}
